<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Collection;
use App\Models\Company;
use App\Models\Education;
use App\Models\Item;
use App\Models\Job;
use App\Models\Position;
use App\Models\Resume;
use App\Models\Staff;
use App\Models\User;
use DB;
use Illuminate\Http\Request;
use Validator;

class ResumeController extends Controller {
	private $user;
	private $role_flag;
	public function __construct() {
		if (\Auth::guard('api')->check()) {
			$getUser = \Auth::guard('api')->user();
			$user = User::find($getUser->id);
			if (!$this->getDevice()) {
				//app
				$user->company_id = $user->appcompany_id;
			}
			$this->user = $user;
			$company = \App\Models\Company::find($this->user->company_id);
			$this->role_flag = $company->role_flag;
		}
	}
	public function all(Request $request) {
		$type = $request->input('type');
		if (empty($type)) {
			$type = 1;
		}
		if (!in_array($type, [1, 2])) {
			return $this->respond('empty_error');
		}
		$user = User::find($this->user->id);
		$company_id = $this->user->company_id;
		$steps = DB::table('companies as a')
			->join('flows as b', 'a.id', '=', 'b.company_id')
			->join('steps as c', 'b.id', '=', 'c.flow_id')->where(['a.id' => $company_id, 'c.status' => 0])
			->select('c.name')->distinct('c.name')->get();

		$page = $this->page($request);
		$query = DB::table('resumes as a')->where(['a.status' => 0, 'a.company_id' => $company_id]);
		if ($type == 1) {
			//1:模糊查询
			$job = $request->input('job');
			$step = $request->input('step');
			$edu = $request->input('edu');
			if (!empty($job)) {
				$query->where('a.is_job', '=', $job);
			}
			if (!empty($edu)) {
				$query->where('a.edu', '=', $edu);
			}
			if (!empty($step)) {
				$query->where('a.step_name', '=', $step);
			}
		}
		if ($type == 2) {
			//2:高级搜素
			$keyword = $request->input('keyword');
			$query->where(function ($query) use ($keyword) {
				if (!empty($keyword) || $keyword == '0') {
					$query->orwhere('a.position', 'like', '%' . $keyword . '%');
					$query->orwhere('a.name', 'like', '%' . $keyword . '%');
					$query->orwhere('a.company_name', 'like', '%' . $keyword . '%');
				}
			});
		}
		$total_item = $query->orderBy('a.id', 'desc')->get();
		if (empty($total_item)) {
			return $this->respond('get_ok', ['item' => [], 'step' => $steps, 'count' => 0, 'pageNum' => 0]);
		}
		$item = array_slice($total_item->toArray(), $page['skip'], $page['take']);
		$count = count($total_item);
		$data['count'] = $count;
		$pageNum = ceil($count / $page['take']);
		$data['pageNum'] = $pageNum;
		$data['item'] = $item;
		$data['step'] = $steps;
		return $this->respond('get_ok', $data);
	}
	//pc简历首页
	public function getAll(Request $request) {
		$type = $request->input('type');
		$company_id = $this->user->company_id;
		$page = $this->page($request);
		$query = DB::table('resumes as a')->where(['a.status' => 0, 'a.company_id' => $company_id])->join('users as b', 'a.owner_id', '=', 'b.id')->leftJoin('positions as c', 'a.position_id', '=', 'c.id');
		$name = $request->input('name');
		if (!empty($name) || $name == '0') {
			$query->where('a.name', 'like', '%' . $name . '%');
		}
		$companyName = $request->input('companyName');
		if (!empty($companyName) || $companyName == '0') {
			$query->where('a.company_name', 'like', '%' . $companyName . '%');
		}
		$position = $request->input('position');
		if (!empty($position) || $position == '0') {
			$query->where('a.position', 'like', '%' . $position . '%');
		}
		$job = $request->input('job');
		if (!empty($job)) {
			$query->where('a.is_job', '=', $job);
		}
		$sex = $request->input('sex');
		if (!empty($sex)) {
			$query->where('a.sex', '=', $sex);
		}
		$edu = $request->input('edu');
		if (!empty($edu)) {
			$query->where('a.edu', '=', $edu);
		}
		$position_id = $request->input('positionId');
		if (!empty($position_id)) {
			$query->where('a.position_id', '=', $position_id);
		}
		$total_item = $query->select('a.*', 'c.name as position_name', 'b.name as owner_name')->orderBy('a.id', 'desc')->get();
		if (empty($total_item)) {
			return $this->respond('get_ok', ['item' => [], 'count' => 0, 'pageNum' => 0]);
		}
		if ($type == 1) {
			//关联简历
			$pid = $request->input('pid');
			if (empty($pid)) {
				return $this->respond('empty_error');
			}
			$get_resume_ids = Resume::where(['status' => 0, 'company_id' => $company_id, 'position_id' => $pid])->pluck('id');
			return $this->respond('get_ok', ['item' => $total_item, 'ids' => $get_resume_ids]);
		}
		$item = array_slice($total_item->toArray(), $page['skip'], $page['take']);
		$count = count($total_item);
		$data['count'] = $count;
		$pageNum = ceil($count / $page['take']);
		$data['pageNum'] = $pageNum;
		$data['item'] = $item;
		return $this->respond('get_ok', $data);
	}
	//获取单条记录
	public function get($id) {
		$model = Resume::find($id);
		if (!empty($model)) {
			if ($model->status == 1) {
				return response()->json(['code' => 500, 'msg' => '该简历已经被删除！']);
			}
			$com = Company::find($this->user->company_id);
			if ($model->company_id != $this->user->company_id) {
				$com1 = Company::find($model->company_id);
				return response()->json(['code' => 500, 'msg' => '请切换到【' . $com1->name . '】公司下！']);
			}
			$collection_status = Collection::where(['user_id' => $this->user->id, 'company_id' => $this->user->company_id, 'obj_id' => $id, 'type' => 1, 'status' => 0])->first();
			$model['cstatus'] = $collection_status ? 1 : 0;
			$staff = Staff::where(['user_id' => $model->owner_id, 'company_id' => $model->company_id, 'status' => 0])->first();
			if (!empty($staff)) {
				$model['own_name'] = $staff->name;
			} else {
				$model['own_name'] = '';
			}
			$staff_name = Staff::where(['user_id' => $this->user->id, 'company_id' => $model->company_id, 'status' => 0])->first();
			if (!empty($staff_name)) {
				$model['user_name'] = $staff_name->name;
			} else {
				$model['user_name'] = '';
			}
			$position = Position::where(['id' => $model->position_id, 'status' => 0])->first();
			if (!empty($position)) {
				$model['position_name'] = $position->name;
			} else {
				$model['position_name'] = '';
			}
			$attachment = $model->attachment;
			if (!empty($attachment)) {
				$ext = substr($attachment, strrpos($attachment, '.') + 1);
				if (in_array(strtolower($ext), ['png', 'jpg', 'pdf'])) {
					$attachment = 'api/v1/resume/upload?file=' . $model->attachment;
				}
			}
			$model['attachment'] = $attachment;
			$get_status = DB::select('select id from resumes where id=? and step_id>=1 and (ask_status!=2||ask_status=0) and (check_status=0||check_status=3) and status=0 limit 1', [$id]);
			$check_resume_status = Resume::where(['status' => 0, 'id' => $id, 'ask_status' => 1, 'check_status' => 1])->first();
			if (!empty($get_status) || !empty($check_resume_status)) {
				$model->type = 3; //进入流程
			} else {
				$model->type = ($this->user->id == $model->owner_id) ? 1 : 2;
				//1：启动 2：申请
			}
			$model->hide_id = \Hashids::encode($id);
			$data['resume'] = $model;
			$data['job'] = Job::where(['resume_id' => $id, 'status' => 0])->orderBy('id', 'desc')->get();
			$data['item'] = Item::where(['resume_id' => $id, 'status' => 0])->orderBy('id', 'desc')->get();
			$data['edu'] = Education::where(['resume_id' => $id, 'status' => 0])->orderBy('id', 'desc')->get();
			return $this->respond('get_ok', $data);
		}
		return $this->respond('get_error');
	}
	//新增保存
	public function add(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		$roleType = $request->input('roleType');
		if ($roleType == 1) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('resume_add') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('resume_add')) {
					return $this->respond('no_auth');
				}
			}
			return $this->respond('op_ok');
		}
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('resume_add') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('resume_add')) {
				return $this->respond('no_auth');
			}
		}
		$validator = Validator::make($request->all(), Resume::$rules, Resume::$message);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$m = new Resume();
		$mobile = $request->input('mobile');
		$check_mobile = Resume::where(['status' => 0, 'mobile' => $mobile, 'company_id' => $this->user->company_id])->first();
		if (!empty($check_mobile)) {
			return response()->json(['code' => 500, 'msg' => '手机号重复，请更换手机号！']);
		}
		$m->user_id = $this->user->id;
		$m->owner_id = $this->user->id;
		if ($request->hasFile('image')) {
			$image = $m->upload_img($request);
			$m->image = 'storage/' . $image;
		}
		$m->name = $request->input('name');
		$m->company_id = $this->user->company_id;
		$m->sex = $request->input('sex');
		$m->mobile = $mobile;
		$m->is_job = $request->input('isJob');
		$m->birthday = $request->input('birthday');
		$m->email = $request->input('email');
		$m->area = $request->input('area');
		$positionId = $request->input('positionId');
		if (!empty($positionId)) {
			$m->position_id = $positionId;
		}
		$m->position = $request->input('position');
		$m->job_date = $request->input('jobDate');
		$result = $m->save();
		if ($result) {
			return $this->respond('add_ok', ['id' => $m->id]);
		}
		return $this->respond('add_error');
	}
	//更新保存
	public function put(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		$roleType = $request->input('roleType');
		if ($roleType == 1) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('resume_edit') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('resume_edit')) {
					return $this->respond('no_auth');
				}
			}
			return $this->respond('op_ok');
		}
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('resume_edit') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('resume_edit')) {
				return $this->respond('no_auth');
			}
		}
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '简历id不能为空']);
		}
		$validator = Validator::make($request->all(), Resume::$rules, Resume::$message);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$model = new Resume();
		$m = $model::find($id);
		if (empty($m)) {
			return $this->respond('get_error');
		}
		if ($request->hasFile('image')) {
			$m->image = 'storage/' . $m->upload_img($request);
		}
		$mobile = $request->input('mobile');
		$check_mobile = Resume::where(['status' => 0, 'mobile' => $mobile, 'company_id' => $this->user->company_id])->where('id', '!=', $id)->first();
		if (!empty($check_mobile)) {
			return response()->json(['code' => 500, 'msg' => '手机号重复，请更换手机号！']);
		}
		$m->name = $request->input('name');
		$m->sex = $request->input('sex');
		$m->mobile = $mobile;
		$m->email = $request->input('email');
		$m->is_job = $request->input('isJob');
		$m->birthday = $request->input('birthday');
		$m->area = $request->input('area');
		$m->position = $request->input('position');
		$m->job_date = $request->input('jobDate');
		$positionId = $request->input('positionId');
		if (!empty($positionId)) {
			$m->position_id = $positionId;
		}
		$result = $m->save();
		if ($result) {
			return $this->respond('update_ok', ['id' => $id]);
		}
		return $this->respond('update_error');
	}
	//上传简历附件
	public function uploadFile(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '简历id不能为空']);
		}
		$m = Resume::find($id);
		if (empty($m)) {
			return $this->respond('get_error');
		}
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (empty($m->attachment)) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('resume_add') && !$user->can('resume_edit') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('resume_add') && !$user->can('resume_edit')) {
					return $this->respond('no_auth');
				}
			}
		} else {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('resume_edit') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('resume_edit')) {
					return $this->respond('no_auth');
				}
			}
		}

		$file = $request->file('attachment');
		$name = $request->input('name');
		if (empty($name)) {
			return response()->json(['code' => 500, 'msg' => '简历附件名称不能为空']);
		}
		if (!$request->hasFile('attachment')) {
			return response()->json(['code' => 500, 'msg' => '上传附件为空或无效']);
		}
		if (!$request->file('attachment')->isValid()) {
			return response()->json(['code' => 500, 'msg' => $file->getErrorMessage()]);
		}
		$ext = $file->getClientOriginalExtension();
		if (!in_array(strtolower($ext), ['png', 'jpg', 'doc', 'docx', 'pdf'])) {
			return response()->json(['code' => 500, 'msg' => '只允许上传png、jpg、doc、docx、pdf格式的图片']);
		}
		if ($file->getClientSize() > (10 * 1024 * 1024)) {
			return response()->json(['code' => 500, 'msg' => '图片大小不能超过10M']);
		}
		$newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
		$savePath = 'attachment/' . date('Ym', time()) . '/' . $newFileName;
		$bytes = \Storage::put(
			$savePath,
			file_get_contents($file->getRealPath())
		);
		if (!\Storage::exists($savePath)) {
			return response()->json(['code' => 500, 'msg' => '上传简历附件出错,请重试']);
		}
		$path = 'storage/' . $savePath;
		$m->attachment = $path;
		$m->attachment_name = $name;
		$result = $m->save();
		if ($result) {
			if (in_array(strtolower($ext), ['png', 'jpg', 'pdf'])) {
				$path = 'api/v1/resume/upload?file=' . $path;
			}
			return $this->respond('op_ok', ['name' => $name, 'path' => $path]);
		}
		return $this->respond('op_error');
	}
	/**
	 * 删除简历附件
	 */

	public function removeFile(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('resume_edit') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('resume_edit')) {
				return $this->respond('no_auth');
			}
		}
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '简历id不能为空']);
		}
		$m = Resume::find($id);
		if (empty($m)) {
			return $this->respond('get_error');
		}
		$savePath = $m->attachment;
		$m->attachment = '';
		$m->attachment_name = '';
		if (!empty($savePath)) {
			$savePath = substr($savePath, 8);
		}
		$result = $m->save();
		if ($result) {
			if (\Storage::exists($savePath)) {
				\Storage::delete($savePath);
			}
			return $this->respond('delete_ok');
		}
		return $this->respond('delete_error');

	}
	//上传图像
	public function uploadImage(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '简历id不能为空']);
		}
		$m = Resume::find($id);
		if (empty($m)) {
			return $this->respond('get_error');
		}
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (empty($m->image)) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('resume_add') && !$user->can('resume_edit') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('resume_add') && !$user->can('resume_edit')) {
					return $this->respond('no_auth');
				}
			}
		} else {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('resume_edit') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('resume_edit')) {
					return $this->respond('no_auth');
				}
			}
		}
		$file = $request->file('image');
		if (!$request->hasFile('image')) {
			return response()->json(['code' => 500, 'msg' => '上传文件为空或无效']);
		}
		if (!$request->file('image')->isValid()) {
			return response()->json(['code' => 500, 'msg' => $file->getErrorMessage()]);
		}
		$ext = $file->getClientOriginalExtension();
		if (!in_array(strtolower($ext), ['png', 'jpg', 'jpeg'])) {
			return response()->json(['code' => 500, 'msg' => '只允许上传png、jpg、jpeg格式的图片']);
		}
		if ($file->getClientSize() > (2 * 1024 * 1024)) {
			return response()->json(['code' => 500, 'msg' => '图片大小不能超过2M']);
		}
		$newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
		$savePath = 'image/' . date('Ym', time()) . '/' . $newFileName;
		$bytes = \Storage::put(
			$savePath,
			file_get_contents($file->getRealPath())
		);
		if (!\Storage::exists($savePath)) {
			return response()->json(['code' => 500, 'msg' => '上传文件出错,请重试']);
		}
		$path = 'storage/' . $savePath;
		$m->image = $path;
		$result = $m->save();
		if ($result) {
			return $this->respond('op_ok', ['path' => $path]);
		}
		return $this->respond('op_error');
	}
	//删除简历
	public function remove(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('resume_remove') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('resume_remove')) {
				return $this->respond('no_auth');
			}
		}
		$id = $request->input('id');
		if (empty($id) || !is_array($id)) {
			return $this->respond('empty_error');
		}
		$result = Resume::whereIn('id', $id)->update(['status' => 1]);
		if ($result) {
			return $this->respond('delete_ok');
		}
		return $this->respond('delete_error');
	}

	public function collection(Request $request) {
		$type = $request->input('type');
		$obj_id = $request->input('objId');
		if (!in_array($type, [1, 2]) || empty($obj_id)) {
			return response()->json(['code' => 500, 'msg' => '参数为空或无效']);
		}
		$data = Collection::where(['user_id' => $this->user->id, 'company_id' => $this->user->company_id, 'type' => $type, 'obj_id' => $obj_id, 'status' => 0])->first();
		if (!empty($data)) {
			return response()->json(['code' => 500, 'msg' => '该简历或职位已收藏，不能重复收藏']);
		}
		$model = new Collection;
		$model->user_id = $this->user->id;
		$model->type = $type;
		$model->obj_id = $obj_id;
		$model->company_id = $this->user->company_id;
		$result = $model->save();
		if ($result) {
			return $this->respond('op_ok');
		}
		return $this->respond('op_error');
	}

	public function cancel(Request $request) {
		$type = $request->input('type');
		$obj_id = $request->input('objId');
		if (!in_array($type, [1, 2]) || empty($obj_id)) {
			return response()->json(['code' => 500, 'msg' => '参数为空或无效']);
		}
		$data = Collection::where(['user_id' => $this->user->id, 'company_id' => $this->user->company_id, 'type' => $type, 'obj_id' => $obj_id, 'status' => 0])->first();
		if (empty($data)) {
			return response()->json(['code' => 500, 'msg' => '请先收藏该简历或职位']);
		}
		$model = Collection::find($data->id);
		$model->status = 1;
		$result = $model->save();
		if ($result) {
			return $this->respond('op_ok');
		}
		return $this->respond('op_error');
	}
	public function downloadImage(Request $request) {
		$file = $request->input('file');
		if (!empty($file)) {
			header('Content-type: octet/stream');
			header('Content-disposition: attachment; filename=' . $file . ';');
			header('Content-Length: ' . filesize($file));
			readfile($file);
		}
		exit;
	}

	public function batchAdd(Request $request) {
		$user = $this->user;
		$resume = $request->resume;
		$job = $request->job;
		$item = $request->item;
		$edu = $request->edu;
		$time = time();
		$resume['user_id'] = $user->id;
		$resume['owner_id'] = $user->id;
		$resume['company_id'] = $user->company_id;
		$resume['created_at'] = $time;
		$resume['updated_at'] = $time;
		\Log::info('user' . json_encode($user->toArray()));
		\Log::info('resumes' . json_encode($resume));
		\Log::info('job' . json_encode($job));
		\Log::info('item' . json_encode($item));
		\Log::info('edu' . json_encode($edu));
		$check_mobile = [];
		if (empty($resume['name'])) {
			return response()->json(['code' => 500, 'msg' => '姓名不能为空']);
		}
		if (isset($resume['mobile']) && !empty($resume['mobile'])) {
			$check_mobile = Resume::where(['status' => 0, 'company_id' => $user->company_id, 'mobile' => $resume['mobile']])->first();
			if (!empty($check_mobile)) {
//更新简历
				$check_mobile->name = $resume['name'];
				$check_mobile->sex = $resume['sex'];
				$check_mobile->is_job = $resume['is_job'];
				$check_mobile->birthday = $resume['birthday'];
				$check_mobile->position = $resume['position'];
				$check_mobile->edu = $resume['edu'];
				$check_mobile->company_name = $resume['company_name'];
				$check_mobile->email = $resume['email'];
				$check_mobile->user_id = $user->id;
				$check_mobile->owner_id = $user->id;
				$check_mobile->company_id = $user->company_id;
				$max_date = 0;
				$get_date_arr = [];
				if (!empty($job)) {
					foreach ($job as $key => $value) {
						$get_date_arr[] = $value['start_date'];
					}
					$max_date = max($get_date_arr);
				}
				$check_job = Job::where(['status' => 0, 'resume_id' => $check_mobile->id])->orderBy('start_date', 'desc')->select('id', 'start_date')->first();
				if (!empty($check_job) && $check_job->start_date >= $max_date) {
					return response()->json(['code' => 500, 'msg' => '重复简历！']);
				}
			}
		}
		//开启事务
		DB::beginTransaction(); //新增简历
		try {
			//中间逻辑代码
			if (!empty($check_mobile)) {
				$check_mobile->save();
				$sid = $check_mobile->id;
				Job::where(['status' => 0, 'resume_id' => $sid])->update(['status' => 1]);
				Item::where(['status' => 0, 'resume_id' => $sid])->update(['status' => 1]);
				Education::where(['status' => 0, 'resume_id' => $sid])->update(['status' => 1]);
			} else {
				$sid = DB::table('resumes')->insertGetId($resume);
			}
			if (!empty($job)) {
				foreach ($job as $key => $value) {
					$value['resume_id'] = $sid;
					$value['created_at'] = $time;
					$value['updated_at'] = $time;
					Job::insert($value);
				}
				
			}
			if (!empty($item)) {
				foreach ($item as $key => $va1) {
					$va1['resume_id'] = $sid;
					$va1['created_at'] = $time;
					$va1['updated_at'] = $time;
					Item::insert($va1);
				}
			}
			if (!empty($edu)) {
				foreach ($edu as $key => $va2) {
					$va2['resume_id'] = $sid;
					$va2['created_at'] = $time;
					$va2['updated_at'] = $time;
					Education::insert($va2);
				}
			}
			DB::commit();
			return $this->respond('add_ok');
		} catch (\Exception $e) {
			//接收异常处理并回滚
			\Log::info('简历批量添加失败：' . json_encode($e));
			DB::rollBack();
			return $this->respond('add_error');
		}
	}
	//获取职位列表
	public function position() {
		//获取职位
		$company_id = $this->user->company_id;
		$position = Position::where(['company_id' => $company_id, 'is_use' => 1, 'status' => 0])->select('id', 'name')->get();
		return $this->respond('get_ok', $position);
	}
	//取消职位关联
	public function cancelPosition(Request $request) {
		$id = $request->input('id');
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '简历id不能为空']);
		}
		$m = Resume::find($id);
		if (empty($m)) {
			return $this->respond('get_error');
		}
		$m->position_id = 0;
		$result = $m->save();
		if ($result) {
			return $this->respond('op_ok');
		}
		return $this->respond('op_error');
	}
	//职位关联简历
	public function addPosition(Request $request) {
		$company_id = $this->user->company_id;
		$positionId = $request->input('pid');
		$ids = $request->input('ids');
		if (empty($positionId)) {
			return $this->respond('empty_error');
		}
		$m = Position::find($positionId);
		if (empty($m)) {
			return $this->respond('get_error');
		}
		if ($m->is_use == 2) {
			return response()->json(['code' => 500, '职位处于关闭状态不能关联简历！']);
		}
		$id_arr = explode(',', $ids);
		//开启事务
		DB::beginTransaction();
		try {
			//中间逻辑代码
			Resume::where(['company_id' => $company_id, 'status' => 0, 'position_id' => $positionId])->update(['position_id' => 0]);
			if (!empty($ids)) {
				Resume::whereIn('id', $id_arr)->where('company_id', $company_id)->update(['position_id' => $positionId]);
			}
			DB::commit();
			return $this->respond('op_ok');
		} catch (\Exception $e) {
			//接收异常处理并回滚
			DB::rollBack();
			return $this->respond('op_error');
		}
	}
	public function changeStatus(Request $request) {
		$id = $request->input('id');
		$resume = Resume::where(['status' => 0, 'id' => $id])->first();
		if (empty($resume)) {
			return $this->respond('get_error');
		}
		if ($resume->is_job == 4) {
			return response()->json(['code' => 500, 'msg' => '该简历已经是已离职状态']);
		}
		if ($resume->is_job != 3) {
			return response()->json(['code' => 500, 'msg' => '该员工未入职公司，无法设置']);
		}
		$resume->is_job = 4;
		$result = $resume->save();
		if ($result) {
			return $this->respond('op_ok');
		}
		return $this->respond('op_error');
	}
	//简历导入匹配信息添加
	public function plug(Request $request) {
		$file = $request->file('file');
		$flag = $request->input('type');
		if (empty($file)) {
			return $this->respond('empty_error');
		}
		// 获取文件后缀名
		$exe = $file->getClientOriginalExtension();

		/*if (!in_array($exe, ['doc', 'docx'])) {
			return response()->json(array('code' => 500, 'msg' => '请上传后缀名为doc、docx的文件'));
		}*/

		/*$shell = "unoconv -f txt D:/wwwroot/ATS/public/uploads/123.docx";
			    $shell2 = "cat D:/wwwroot/ATS/public/uploads/123.txt";
			     $status=[];
			    $code=0;
			    echo "<pre>";

			    system ($shell, $status);
			    dd($status);

			    echo "</pre>";
		*/
		//注意shell命令的执行结果和执行返回的状态值的对应关系
		/*$shell = "<font color='red'>$shell</font>";
	    $shell2 = "<font color='red'>$shell2</font>";
	    var_dump($code);
	    dd($status);
	    if( $status ){
	        echo "shell命令{$shell}执行失败";
	    } else {
	        echo "shell命令{$shell}成功执行";
	    }
*/
/*		$word = new \COM("word.application") or die("Can't start Word!");
// 显示目前正在使用的Word的版本号
echo "Loading Word, v. {$word->Version}<br>";
// 把它的可见性设置为0（假），如果要使它在最前端打开，使用1（真）
// to open the application in the forefront, use 1 (true)
$word->visible = 0;

//打?一个文档
$word->Documents->OPen(public_path('/storage/15306072375b3b3685314e0.doc'));
//读取文档内容

$test= $word->ActiveDocument->Content->Text;

echo $test; exit;*/
		$res = [];
		$realPath = $file->getRealPath(); //临时文件的绝对路径
		$type = $file->getClientMimeType(); // image/jpeg

		// 上传文件
		$filename = date('YmdHis') . uniqid() . '.' . $exe;
		// 使用我们新建的uploads本地存储空间（目录）
		//这里的uploads是配置文件的名称
		/*$bool = \Storage::put($filename, file_get_contents($realPath));
		var_dump($filename);*/

		/*exec(file_get_contents('./storage/123.txt'),$arr,$code);
			        var_dump($code);
		*/
		/*$ss = file_get_contents('php://input');
		dd($ss);*/
		$filename = "201807111537225b45b3b289e1e.doc";
		$filepath = './storage/' . $filename;
		$fp = fopen($filepath, "rb");
		Header("Content-type: application/octet-stream");
		Header("Accept-Ranges: bytes");
		Header("Content-Disposition: attachment; filename=xxx.pdf");
		$buffer = 1024;
		while (!feof($fp)) {
			$file_con = fread($fp, $buffer);
			echo $file_con;
		}
		fclose($fp);
		dd(111);

		$phpWord = new \PhpOffice\PhpWord\PhpWord();
		$section = $phpWord->addSection();
		$content = file_get_contents($filepath);
		$con1 = $this->html2text($content);
		$section->addText($con1);
		$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
		$objWriter->save('helloWorld.html');
		//$cont = new \PhpOffice\PhpWord\TemplateProcessor($filepath);
		//$xml = $cont->tempDocumentMainPart;
		//dd($cont);

		$phpWord = new \PhpOffice\PhpWord\PhpWord();
		$cont = \PhpOffice\PhpWord\IOFactory::load($filepath, 'MsDoc');
		dd($cont);

		$handle = fopen($filepath, "rb"); //打开文件
		$contents = fread($handle, 8080); //读两字节，也就是一个汉字
		$hex = bin2hex($contents); //二进制转成16进制
		$str = [];
		$string = '';
		for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
			$string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
		}
		$string = iconv("gb2312", "utf-8", $string);

		dd($string);
		/*$handle = fopen($filepath, 'rb');
			$content = '';
			while (!feof($handle)) {
			$content .= fread($handle, 8080);
			}
			echo $content;
		*/
		//echo readfile($filepath);exit;
		//html格式文件解析
		if ($flag == 1) {
			$content = file_get_contents($filepath);
			//dd($content);
			$con1 = $this->html2text($content);
			//dd(base64_decode($content));
			//file_get_contents('./storage/11.txt',$con1);
			$str_encoding = mb_convert_encoding($con1, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'); //转换字符集（编码）
			$arr = explode("\r\n", $str_encoding); //转换成数组
			//去除值中的空格
			foreach ($arr as &$row) {
				$row = trim($row);
			}
			//dd($arr);
			//dd($arr[0]);
			//得到后的数组
			if (count($arr) == 1) {
				$arr = explode("\n", $arr[0]);
			}
			$data = [];
			foreach ($arr as $key => $value) {
				$value = trim($value);
				if (!empty($value)) {
					$data[] = $value;
				}
			}
		} else {
			$content = file_get_contents($filepath);
			//dd($content);
			//$ss = $this->fetch_big_file($content);
			//dd(base64_decode($content));
			//dd($content);
			dd($this->BinToStr($content));
		}
		dd($data);
		//move_uploaded_file
		/*$upload_re=move_uploaded_file($realPath,'./uploads/'.$filename);
		dd($upload_re);*/

		/*$phpWord = new \PhpOffice\PhpWord\PhpWord();
			// 新的页面
			$section = $phpWord->addSection();
			// 简单文本
			$section->addTitle('CA重庆起止-阿联酋7天5晚', 1);
			$section->addText('阿拉伯联合酋长国（The United Arab Emirates），简称为阿联酋，位于阿拉伯半岛东部，北濒波斯湾，西北与卡塔尔为邻，西和南与沙特阿拉伯交界，东和东北与阿曼毗连海岸线长734公里，总面积83600平方公里，首都阿布扎比。!');
			// 两个换行符
			$section->addTextBreak(2);
			$section->addText('第一天：请各位贵宾出发当日15:30于重庆江北国际机场集中，搭乘中国国际航空公司下午航班（CA451（1840/2215））前往迪拜。抵达后迪拜国际机场，照眼角膜后（无须填入境卡）入境（过关时间约1.5小时）中文导游接机，后前往酒店入住休息');

			$section->addTextBreak();
			//超链接
			$section->addLink('http://keketour.me', '可可兔首页超链接');
			$section->addTextBreak();

			$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
		*/
		/*$getHtml = file_get_contents($realPath);
					//dd($getHtml);
					$pre="<table class=MsoNormalTable>(.*)</table>";
			        preg_match($pre,$getHtml,$content);
		*/
		//echo $filename;
		//$exe='docx'; //Sample_11_ReadWord97.doc  201807040957385b3c2992e2d17.doc
		/*$filepath = './storage/' . $filename;
			if ($exe == 'doc') {
				$cont = \PhpOffice\PhpWord\IOFactory::load($filepath, 'MsDoc');
			} else if ($exe == 'docx') {
				$cont = \PhpOffice\PhpWord\IOFactory::load($filepath);
			}
			dd($cont);
			$writer = \PhpOffice\PhpWord\IOFactory::createWriter($cont, 'Word2007');
	        $writer->save('./storage/hello123.docx');
	        $phpWord = \PhpOffice\PhpWord\IOFactory::load('./storage/hello123.docx');
	        $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
	        $xmlWriter->save('./storage/hello123.html');
			$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($cont, 'HTML');
*/
		/*$cont = new \PhpOffice\PhpWord\TemplateProcessor($filepath);
			$xml = $cont->tempDocumentMainPart;
		*/
		//$filepath = './uploads/' . '123.docx';
		/*$cont =\PhpOffice\PhpWord\IOFactory::load($filepath);
			$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($cont, 'ODText');
	        $objWriter->save('./storage/123.odt');
*/
		//$ss=file_get_contents($filepath);
		//dd($ss);
		/*		$content = shell_exec($filepath);

dd($content);*/

		/*dd($xml);
			dd($sss);
		*/
		//$source = "resources/{$name}.doc";
		// Save file
		/*$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf', 'HTML' => 'html', 'PDF' => 'pdf');
		dd($this->write($cont, basename(__FILE__, '.php'), $writers));*/
		// 保存pdf文档
		/*$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($cont, "PDF");
$xmlWriter->save("./storage/123.pdf");*/
/*$data1=$cont->getSections()[0]->getElements();
foreach ($data1 as $key => $value) {
dd($value->type);
}
dd(5656);*/
		/*foreach ($cont as $key => $value) {
			echo 1;
			\Log::info('valeue:'.json_encode($value));
		}*/
		//$cont = \Storage::get($filename);

	}
	//html格式转文本格式
	public function html2text($str) {
		$str = preg_replace("/<style .*?<\/style>/is", "", $str);
		$str = preg_replace("/<script .*?<\/script>/is", "", $str);
		$str = preg_replace("/<br \s*\/?\/>/i", "\n", $str);
		$str = preg_replace("/<\/?p>/i", "\n\n", $str);
		$str = preg_replace("/<\/?td>/i", "\n", $str);
		$str = preg_replace("/<\/?div>/i", "\n", $str);
		$str = preg_replace("/<\/?blockquote>/i", "\n", $str);
		$str = preg_replace("/<\/?li>/i", "\n", $str);
		$str = preg_replace("/\&nbsp\;/i", "", $str);
		$str = preg_replace("/\&nbsp/i", "", $str);
		$str = preg_replace("/\&amp\;/i", "&", $str);
		$str = preg_replace("/\&amp/i", "&", $str);
		$str = preg_replace("/\&lt\;/i", "<", $str);
		$str = preg_replace("/\&lt/i", "<", $str);
		$str = preg_replace("/\&ldquo\;/i", '"', $str);
		$str = preg_replace("/\&ldquo/i", '"', $str);
		$str = preg_replace("/\&lsquo\;/i", "'", $str);
		$str = preg_replace("/\&lsquo/i", "'", $str);
		$str = preg_replace("/\&rsquo\;/i", "'", $str);
		$str = preg_replace("/\&rsquo/i", "'", $str);
		$str = preg_replace("/\&gt\;/i", ">", $str);
		$str = preg_replace("/\&gt/i", ">", $str);
		$str = preg_replace("/\&rdquo\;/i", '"', $str);
		$str = preg_replace("/\&rdquo/i", '"', $str);
		$str = strip_tags($str);
		$str = html_entity_decode($str, ENT_QUOTES, 'utf-8');
		$str = preg_replace("/\&\#.*?\;/i", "", $str);
		return $str;
	}
	//二进制格式转文本格式
	public function fetch_big_file($srcPath) {
		$info = [];
		set_time_limit(0); // 设置脚本执行时间无限长

		if (!$fpSrc = fopen($srcPath, "rb")) {
			return false;
		}
		do {
			$data = fread($fpSrc, 8192); // 每次读取 8*1024个字节
			if (!$data) {
				break;
			}
			$info[] = $data;
		} while (true);

		fclose($fpSrc);
		return $info;
	}
	public function BinToStr($str) {
		$arr = explode(' ', $str);
		foreach ($arr as &$v) {
			$v = pack("H" . strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));
		}

		return join('', $arr);
	}
	public function receiveStreamFile($receiveFile) {
		$streamData = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';

		if (empty($streamData)) {
			$streamData = file_get_contents('php://input');
		}

		if ($streamData != '') {
			$ret = file_put_contents($receiveFile, $streamData, true);
		} else {
			$ret = false;
		}
		return $ret;
	}

}
